<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 提成记录
 */
class CommissionLog extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'date',
        'type_text',
    ];

    public function getTypeList()
    {
        return ['pick' => __('取件提成'), 'service' => __('维修提成')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getDateAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['updatetime']) ? $data['updatetime'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    //计入提成
    public static function addLog($task,$type,$user_id,$user_nickname,$money,$status=1,$memo='')
    {
        return self::create([
           'type'                   => $type,
           'user_id'                => $user_id,
           'user_nickname'          => $user_nickname,
           'task_id'                => $task->id,
           'order_sn'               => $task->order_sn,
           'car_number'             => $task->car_number,
           'report_number'          => $task->report_number,
           'money'                  => $money,
           'status'                 => $status,
           'memo'                   => $memo,
           'servicedtime'           => $task->ext_arr['serviced_time'],
           'finishtime'             => $task->ext_arr['return_time'],
        ]);
    }

    //查询指定任务下用户的维修提成
    public static function getTaskService($task_id,$user_id)
    {
        return self::where(['type'=>'service','task_id'=>$task_id,'user_id'=>$user_id])->order('createtime desc')->find();
    }


    //全部列表
    public static function getLists($params)
    {
        $user = User::info();
        extract($params);
        $where['user_id'] = $user->id;
        $where['status'] = 1;
        if (isset($keywords) && $keywords) {
            $where['order_sn | report_number'] = ['like', '%'.$keywords.'%'];
        }
        if (isset($starttime) && $starttime && isset($endtime) && $endtime) {
            $startTime = strtotime($starttime);
            $endTime = strtotime($endtime. '+1 day');
            $where['updatetime'] = ['between', [$startTime, $endTime]];
        }
        $data = self::where($where)->order('updatetime desc')->paginate(10);
        foreach($data->items() as &$item){
            if ($item['type'] == 'service'){
                $service = TasksService::getTaksLogs($item['user_id'],$item['task_id']);
                $item['service'] = $service;
            }else{
                $item['service'] = null;
            }
        }
        return $data;
    }

}
